﻿using Newtonsoft.Json;
using Newtonsoft.Json.Bson;

namespace CoverageRunner.Core;

public class ConfigureSerializer
{
    public static RunnerConfig? FromStream(Stream data)
    {
        using (var reader = new BsonReader(data))
        {
            JsonSerializer serializer = new JsonSerializer();

            RunnerConfig? cfg = serializer.Deserialize<RunnerConfig>(reader);

            return cfg;
        }
    }

    public static void ToStream(RunnerConfig cfg, Stream os)
    {
        using (var writer = new BsonWriter(os))
        {
            JsonSerializer serializer = new JsonSerializer();
            
            serializer.Serialize(writer, cfg);
        }
    }

    public static RunnerConfig? FromFile(string path)
    {
        try
        {
            using (var stream = new FileStream(path, FileMode.Open))
            {
                return FromStream(stream);
            }
        }
        catch (Exception)
        {
            return null;
        }
    }

    public static void SaveToFile(RunnerConfig cfg, string path)
    {
        var dir = Path.GetDirectoryName(path);
        if (dir != null && !Directory.Exists(dir))
            Directory.CreateDirectory(dir);
        else if (dir == null)
            throw new ArgumentException("bad file path!!");

        using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
        {
            stream.SetLength(0);
            ToStream(cfg, stream);
        }
    }
}